package cn.agiledata.bank.linkbank.impl.validate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.agiledata.bank.linkbank.exception.LinkBankException;
import cn.agiledata.bank.linkbank.logic.FieldValidateManager;
import cn.agiledata.bank.linkbank.logic.FieldValidator;

public class FieldValidateManagerImpl implements FieldValidateManager {
    private FieldValidateManager parent;

    private List ignoredFields = new ArrayList(0);

    private FieldValidator[] fieldValidators = new FieldValidator[0];

    public void setParent(FieldValidateManager parsent) {
        this.parent = parsent;
    }

    public void setIgnoredFields(String[] ignoredFields) {
        for (int i = 0; i < ignoredFields.length; i++) {
            this.ignoredFields.add(ignoredFields[i]);
        }
    }

    public void setFieldValidators(FieldValidator[] fieldValidators) {
        this.fieldValidators = fieldValidators;
    }

    public void validateFields(Map values) throws LinkBankException {
        List ignoredFieldList = new ArrayList(this.ignoredFields);
        for (int i = 0; i < this.fieldValidators.length; i++) {
            FieldValidator validator = this.fieldValidators[i];
            String target = validator.getTarget();
            // 忽略数据域
            if (!this.ignoredFields.contains(target)) {
                Object value = values.get(target);
                if (value == null || value instanceof String) {
                    validator.validate((String) value);
                }
                ignoredFieldList.add(target);
            }
        }
        if (this.parent != null) {
            String[] ignoredFields = (String[]) ignoredFieldList
                    .toArray(new String[0]);
            this.parent.setIgnoredFields(ignoredFields);
            this.parent.validateFields(values);
        }
    }
}
